package com.mifengs.mall.ui.openself;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.mall.di.component.DaggerMaterialsSubComponent;
import com.mifengs.mall.di.module.MaterialSubModule;
import com.mifengs.mall.entity.CategoriesBean;
import com.mifengs.mall.entity.City;
import com.mifengs.mall.entity.StoreCertificate;
import com.mifengs.mall.util.GPSUtil;
import com.mifengs.mall.util.ImageLoadUtil;
import com.mifengs.mall.util.LocationUtil;
import com.mifengs.mall.util.TimeUitl;
import com.mifengs.mall.util.Tools;
import com.mifengs.mall.widget.MapContainer;
import com.mifengs.mall.widget.UploadPhotoView.UpLoadPhotoView;
import com.mifengs.mall.widget.UploadPhotoView.UpLoadPhotoViewController;
import com.rey.material.app.BottomSheetDialog;
import com.yiguo.adressselectorlib.AddressSelector;
import com.yiguo.adressselectorlib.CityInterface;
import com.yiguo.adressselectorlib.OnItemClickListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by lynn on 2018/3/19.
 */

public class MaterialSubFragment extends BaseFragment<MaterialSubPresenter> implements EasyPermissions.PermissionCallbacks, MaterialSubContract.View, AMapLocationListener, AMap.OnCameraChangeListener, GeocodeSearch.OnGeocodeSearchListener, UpLoadPhotoView.OnClickUpViewListener {


    @BindView(R.id.time_text)
    TextView timeText;
    @BindView(R.id.contact_name_eidt)
    EditText contactNameEidt;
    @BindView(R.id.contact_phone_eidt)
    EditText contactPhoneEidt;
    @BindView(R.id.license_name_eidt)
    EditText licenseNameEidt;
    @BindView(R.id.license_name_num_eidt)
    EditText LicenseNumberEidt;
    @BindView(R.id.radioTimeInterval)
    RadioButton radioTimeInterval;
    @BindView(R.id.radioLongTime)
    RadioButton radioLongTime;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.business_license_img)
    UpLoadPhotoView businessLicenseImg;
    @BindView(R.id.head_sfz_num_edit)
    EditText headSfzNumEdit;
    @BindView(R.id.sfz_positive_img)
    UpLoadPhotoView sfzPositiveImg;
    @BindView(R.id.sfz_reverse_img)
    UpLoadPhotoView sfzReverseImg;
    @BindView(R.id.hold_sfz_img)
    UpLoadPhotoView holdSfzImg;
    @BindView(R.id.store_name_edidt)
    EditText storeNameEdidt;
    @BindView(R.id.store_photo_img_one)
    UpLoadPhotoView storePhotoImgOne;
    @BindView(R.id.store_photo_img_two)
    UpLoadPhotoView storePhotoImgTwo;
    @BindView(R.id.store_photo_img_three)
    UpLoadPhotoView storePhotoImgThree;
    @BindView(R.id.operate_range_one)
    TextView operateRangeOne;
    @BindView(R.id.operate_range_two)
    TextView operateRangeTwo;
    @BindView(R.id.area_text)
    TextView areaText;
    @BindView(R.id.store_detailed_area_text)
    EditText storeDetailedAreaText;
    @BindView(R.id.map_view)
    MapView mMapView;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    @BindView(R.id.mapContainer_view)
    MapContainer mapContainerView;
    public static final int REQUEST_PERMISSION_LOCATION = 1;
    @BindView(R.id.bt_sub_examine)
    Button btSubExamine;
    @BindView(R.id.bank_card_edidt)
    EditText bankCardEdidt;
    @BindView(R.id.bank_card_name_edidt)
    EditText bankCardNameEdidt;
    @BindView(R.id.bank_card_photo)
    UpLoadPhotoView bankCardPhoto;
    private AMap mAMap;
    private static final int MAP_SCALE = 19;
    private AMapLocationClient mlocationClient;
    private MarkerOptions mCenterMarkerOptions;
    private Marker mCenterMarker;
    private AMapLocationClientOption mLocationOption;
    private boolean isLocal = false;
    private LatLng mLoclatLng;
    private GeocodeSearch mGeocodeSearch;
    private int setTimeType = 1;
    private TimePickerView pvCustomTime;
    private ScheduledExecutorService service;
    private EditText startTime;
    private EditText endTime;
    private int radioIndex = 0;//0:长期、1:时段
    private String licenseStartDate, LicenseEndDate;
    private int intOperateRangeOne, intOperateRangeTwo;
    private int categoriesIndex;
    double longitude, latitude;
    private ArrayList<ImageItem> images;
    private UpLoadPhotoView mSelectUpView;
    private String businessLicenseUrl;
    private String sfzPositiveUrl;
    private String sfzReverseUrl;
    private String holdSfzUrl;
    private String storePhotoOneUrl;
    private String storePhotoTwoUrl;
    private String storePhotoThreeUrl;
    private String bankCardPhotoUrl;
    private int storeType; //店铺类型
    private boolean fail = false; //判断进入界面是否是修改
    private boolean isTimeType = false;
    private int provinceId, cityId, areaId, streetId;
    private String provinceName, cityName, areaName, streetName,storeTypeNameOne,storeTypeNameTwo;
    private BottomSheetDialog bottomSheetDialog;
    private List<CategoriesBean> options1Items = new ArrayList<>();
    private List<String> options1ItemName = new ArrayList<>();
    private ArrayList<City> provincesList = new ArrayList<City>();  //省
    private ArrayList<City> citysList = new ArrayList<City>();  //市
    private ArrayList<City> areasList = new ArrayList<City>();  //区
    private ArrayList<City> streetsList = new ArrayList<City>();  //街道
    public static final String IS_SAVE = "is_save";

    public static MaterialSubFragment newInstance(int storeType, boolean fail) {
        MaterialSubFragment fragment = new MaterialSubFragment();
        Bundle args = new Bundle();
        args.putInt("storeType", storeType);
        args.putBoolean("fail", fail);
        fragment.setArguments(args);
        return fragment;
    }

    Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    pvCustomTime.returnData();
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            storeType = getArguments().getInt("storeType");
            fail = getArguments().getBoolean("fail");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_material_sub, container, false);
        ButterKnife.bind(this, view);
        mMapView.onCreate(savedInstanceState);
        initView();
        return view;
    }

    @Override
    public void initInjector() {
        DaggerMaterialsSubComponent.builder()
                .materialSubModule(new MaterialSubModule(this))
                .build()
                .inject(this);
    }

    private void setOnEditorAction() {
        String digists = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        LicenseNumberEidt.setKeyListener(DigitsKeyListener.getInstance(digists));
        headSfzNumEdit.setKeyListener(DigitsKeyListener.getInstance(digists));
    }

    private void initView() {
        if (storeType == 0) {
            btSubExamine.setText(getResources().getString(R.string.next_step));
        } else {
            btSubExamine.setText(getResources().getString(R.string.sub_examine));
        }
        if (fail) {
            mPresenter.getStoreCertificate();
        }
        needLoc();
        mapContainerView.setScrollView(scrollView);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.radioLongTime:
                        radioIndex = 0;
                        timeText.setVisibility(View.GONE);
                        isTimeType = false;
                        break;
                    case R.id.radioTimeInterval:
                        closeKeyboard(radioTimeInterval);
                        if (!isTimeType) {
                            radioIndex = 1;
                            timeText.setVisibility(View.VISIBLE);
                            initCustomTimePicker();
                        }
                        break;
                }
            }
        });
        setUplaodImg();
        setOnEditorAction();

        if(PreferenceUtils.getBooleanPreference(getContext(),IS_SAVE)){
            try {
                StoreCertificate storeCertificate = MallApplication.getInstance().getCacheHelper().getAsSerializable(MaterialSubPresenter.TAG);
                if(storeCertificate!=null){
                    setStoreCertificate(storeCertificate,true);
                    return;
                }
            }catch (Exception e){

            }
        }
    }

    /**
     * 判断图片是否上传成功
     *
     * @return
     */
    private boolean isUploading() {
        if (businessLicenseImg.getController().isUploading() || sfzPositiveImg.getController().isUploading()
                || sfzReverseImg.getController().isUploading()
                || storePhotoImgOne.getController().isUploading()
                || bankCardPhoto.getController().isUploading()) {
            return true;
        }
        return false;
    }

    /**
     * 初始化图片UI
     */
    private void setUplaodImg() {
        businessLicenseImg.setClickUpViewListener(this);
        sfzPositiveImg.setClickUpViewListener(this);
        sfzReverseImg.setClickUpViewListener(this);
        holdSfzImg.setClickUpViewListener(this);
        storePhotoImgOne.setClickUpViewListener(this);
//        storePhotoImgTwo.setClickUpViewListener(this);
//        storePhotoImgThree.setClickUpViewListener(this);
        bankCardPhoto.setClickUpViewListener(this);
        businessLicenseImg.setText("上传营业执照");
        sfzPositiveImg.setText("上传正面照片");
        sfzReverseImg.setText("上传背面照片");
        holdSfzImg.setText("上传业务员与店主合照");
        storePhotoImgOne.setText("上传门头实拍照片");
//        storePhotoImgTwo.setText("上传货柜实拍照片");
//        storePhotoImgThree.setText("上传收银台实拍照片");
        bankCardPhoto.setText("上传银行卡正面照片");
        bankCardPhoto.getController().setUploadListener(new UpLoadPhotoViewController.UploadStatusListener() {
            @Override
            public void success(String imgUrl) {
                bankCardPhotoUrl = imgUrl;
            }

            @Override
            public void fail() {

            }
        });

        businessLicenseImg.getController().setUploadListener(new UpLoadPhotoViewController.UploadStatusListener() {
            @Override
            public void success(String imgUrl) {
                businessLicenseUrl = imgUrl;
            }

            @Override
            public void fail() {

            }
        });
        sfzPositiveImg.getController().setUploadListener(new UpLoadPhotoViewController.UploadStatusListener() {
            @Override
            public void success(String imgUrl) {
                sfzPositiveUrl = imgUrl;
            }

            @Override
            public void fail() {

            }
        });
        sfzReverseImg.getController().setUploadListener(new UpLoadPhotoViewController.UploadStatusListener() {
            @Override
            public void success(String imgUrl) {
                sfzReverseUrl = imgUrl;
            }

            @Override
            public void fail() {

            }
        });
        holdSfzImg.getController().setUploadListener(new UpLoadPhotoViewController.UploadStatusListener() {
            @Override
            public void success(String imgUrl) {
                holdSfzUrl = imgUrl;
            }

            @Override
            public void fail() {

            }
        });
        storePhotoImgOne.getController().setUploadListener(new UpLoadPhotoViewController.UploadStatusListener() {
            @Override
            public void success(String imgUrl) {
                storePhotoOneUrl = imgUrl;
            }

            @Override
            public void fail() {

            }
        });
//        storePhotoImgTwo.getController().setUploadListener(new UpLoadPhotoViewController.UploadStatusListener() {
//            @Override
//            public void success(String imgUrl) {
//                storePhotoTwoUrl = imgUrl;
//            }
//
//            @Override
//            public void fail() {
//
//            }
//        });
//        storePhotoImgThree.getController().setUploadListener(new UpLoadPhotoViewController.UploadStatusListener() {
//            @Override
//            public void success(String imgUrl) {
//                storePhotoThreeUrl = imgUrl;
//            }
//
//            @Override
//            public void fail() {
//
//            }
//        });
    }

    /**
     * 经营范围选择
     */
    private void initCustomOperateRange() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(getContext(), new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                CategoriesBean categoriesBean = options1Items.get(options1);
                if (categoriesIndex == 1) {
                    operateRangeOne.setText(categoriesBean.getValue());
                    storeTypeNameOne = categoriesBean.getValue();
                    intOperateRangeOne = Integer.parseInt(categoriesBean.getKey());
                } else {
                    operateRangeTwo.setText(categoriesBean.getValue());
                    storeTypeNameTwo = categoriesBean.getValue();
                    intOperateRangeTwo = Integer.parseInt(categoriesBean.getKey());
                }
            }
        })
//                        .setSubmitText("确定")//确定按钮文字
//                        .setCancelText("取消")//取消按钮文字
//                        .setTitleText("城市选择")//标题
                .setSubCalSize(20)//确定和取消文字大小
//                        .setTitleSize(20)//标题文字大小
//                        .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.blue))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.blue))//取消按钮文字颜色
//                        .setTitleBgColor(0xFF333333)//标题背景颜色 Night mode
//                        .setBgColor(0xFF000000)//滚轮背景颜色 Night mode
//                        .setContentTextSize(18)//滚轮文字大小
//                        .setTextColorCenter(Color.BLUE)//设置选中项的颜色
                .setTextColorCenter(getResources().getColor(R.color.blue))//设置选中项的颜色
                .setLineSpacingMultiplier(2.0f)//设置两横线之间的间隔倍数
//                        .setLinkage(false)//设置是否联动，默认true
//                        .setLabels("省", "市", "区")//设置选择的三级单位
//                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .setCyclic(false, false, false)//循环与否
//                        .setSelectOptions(1, 1, 1)  //设置默认选中项
//                        .setOutSideCancelable(false)//点击外部dismiss default true
//                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvOptions.setPicker(options1ItemName);
        pvOptions.show();
    }

    /**
     * 时间选择器
     */
    private void initCustomTimePicker() {
        service = Executors.newScheduledThreadPool(100);
        service.scheduleAtFixedRate(new VisibleScheduledExecutor(), 1, 1, TimeUnit.SECONDS);

        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        final String currentTime = sdf.format(selectedDate.getTime());

        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerView.Builder(getContext(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (timeText != null) {
                    if (setTimeType == 1) {
                        startTime.setText(TimeUitl.getTime(date));
                    } else if (setTimeType == 2) {
                        endTime.setText(TimeUitl.getTime(date));
                    }
                }

            }
        })

                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                        startTime = (EditText) v.findViewById(R.id.start_time);
                        endTime = (EditText) v.findViewById(R.id.end_time);
                        startTime.setInputType(InputType.TYPE_NULL);
                        endTime.setInputType(InputType.TYPE_NULL);
                        startTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                            @Override
                            public void onFocusChange(View v, boolean hasFocus) {
                                if (hasFocus) {
                                    setTimeType = 1;
                                    pvCustomTime.returnData();
                                } else {
                                    // 失去焦点
                                }

                            }
                        });
                        endTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                            @Override
                            public void onFocusChange(View v, boolean hasFocus) {
                                if (hasFocus) {
                                    setTimeType = 2;
                                    pvCustomTime.returnData();
                                } else {
                                    // 失去焦点
                                }
                            }
                        });
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (!"".equals(startTime.getText().toString()) && !"".equals(endTime.getText().toString())) {
                                    if (Tools.isTimeCompare(startTime.getText().toString(), endTime.getText().toString())) {
                                        ToastUitl.show("结束时间不能小于开始时间", Toast.LENGTH_SHORT);
                                    } else if (Tools.isTimeCompare(currentTime, endTime.getText().toString())) {
                                        ToastUitl.show("营业执照日期不能小于当前日期", Toast.LENGTH_SHORT);
                                    } else {
                                        licenseStartDate = startTime.getText().toString();
                                        LicenseEndDate = endTime.getText().toString();
                                        pvCustomTime.returnData();
                                        pvCustomTime.dismiss();
                                        setTimeType = 1;
                                        timeText.setText(startTime.getText().toString() + " 至 " + endTime.getText().toString());
                                        service.shutdown();
                                    }

                                } else {
                                    ToastUitl.show("请设置完整的时间", Toast.LENGTH_SHORT);
                                }

                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                                setTimeType = 1;

                            }
                        });
                    }
                })
                .setTextColorCenter(getResources().getColor(R.color.blue))//设置选中项的颜色
                .setContentSize(20)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(0, 0, 0, 40, 0, -40)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFF24AD9D)
                .setDate(selectedDate)
                .build();
        pvCustomTime.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                if (licenseStartDate == null && licenseStartDate == licenseStartDate) {
                    timeText.setText("请设置时间");
                }
                setTimeType = 1;
            }
        });
        pvCustomTime.show();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.bt_sub_examine, R.id.time_text, R.id.business_license_img, R.id.sfz_positive_img, R.id.sfz_reverse_img, R.id.hold_sfz_img, R.id.store_photo_img_one, R.id.store_photo_img_two, R.id.store_photo_img_three, R.id.operate_range_one, R.id.operate_range_two, R.id.area_text, R.id.fl_dingwei})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.time_text:
                isTimeType = false;
                initCustomTimePicker();
                break;
            case R.id.operate_range_one:
                closeKeyboard(operateRangeOne);
                categoriesIndex = 1;
                if (options1Items.size() > 0) {
                    initCustomOperateRange();
                } else {
                    mPresenter.getCategories();
                }
                break;
            case R.id.operate_range_two:
                closeKeyboard(operateRangeTwo);
                categoriesIndex = 2;
                if (options1Items.size() > 0) {
                    initCustomOperateRange();
                } else {
                    mPresenter.getCategories();
                }
                break;
            case R.id.area_text:
                mPresenter.getProvinces();
                break;
            case R.id.fl_dingwei:
                againLoc();
                break;
            case R.id.bt_sub_examine:
                mPresenter.judgeEmpty();
                break;
        }
    }

    /**
     * 显示地址选择的pop
     */
    private void showAddressPickerPop() {
        bottomSheetDialog = new BottomSheetDialog(getContext());
        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.pop_address_picker, null, false);
        AddressSelector addressSelector = (AddressSelector) rootView.findViewById(R.id.address);
        addressSelector.setTabAmount(4);
        addressSelector.setCities(provincesList);
        addressSelector.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void itemClick(AddressSelector addressSelector, CityInterface cityInterface, int tabPosition) {
                switch (tabPosition) {
                    case 0:
                        for (int i = 0; i < provincesList.size(); i++) {
                            City city = provincesList.get(i);
                            if (city.getValue().equals(cityInterface.getCityName())) {
                                mPresenter.getCitys(Integer.parseInt(city.getKey()), addressSelector, tabPosition);
                                provinceId = Integer.parseInt(city.getKey());
                                provinceName = city.getValue();
                            }
                        }
                        break;
                    case 1:
                        for (int i = 0; i < citysList.size(); i++) {
                            City city = citysList.get(i);
                            if (city.getValue().equals(cityInterface.getCityName())) {
                                mPresenter.getAreas(Integer.parseInt(city.getKey()), addressSelector, tabPosition);
                                cityId = Integer.parseInt(city.getKey());
                                cityName = city.getValue();
                            }
                        }
                        break;
                    case 2:
                        for (int i = 0; i < areasList.size(); i++) {
                            City city = areasList.get(i);
                            if (city.getValue().equals(cityInterface.getCityName())) {
                                mPresenter.getStreets(Integer.parseInt(city.getKey()), addressSelector, tabPosition);
                                areaId = Integer.parseInt(city.getKey());

                                areaName = city.getValue();
                            }
                        }
                        break;
                    case 3:
                        for (int i = 0; i < streetsList.size(); i++) {
                            City city = streetsList.get(i);
                            if (city.getValue().equals(cityInterface.getCityName())) {
                                streetId = Integer.parseInt(city.getKey());
                                streetName = city.getValue();
                                areaText.setText(provinceName + cityName + areaName + streetName);
                            }
                        }
                        bottomSheetDialog.dismiss();
                        break;
                }
            }
        });
        addressSelector.setOnTabSelectedListener(new AddressSelector.OnTabSelectedListener() {
            @Override
            public void onTabSelected(AddressSelector addressSelector, AddressSelector.Tab tab) {
                switch (tab.getIndex()) {
                    case 0:
                        addressSelector.setCities(provincesList);
                        break;
                    case 1:
                        addressSelector.setCities(citysList);
                        break;
                    case 2:
                        addressSelector.setCities(areasList);
                        break;
                    case 3:
                        addressSelector.setCities(streetsList);
                        break;
                }
            }

            @Override
            public void onTabReselected(AddressSelector addressSelector, AddressSelector.Tab tab) {

            }
        });
        int screenH = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        bottomSheetDialog.contentView(rootView)
                .heightParam(screenH / 2)
                .inDuration(500)
                .outDuration(500)
//                .inInterpolator(new BounceInterpolator())
//                .outInterpolator(new AnticipateInterpolator())
                .cancelable(true)
                .show();

    }

    /**
     * 初始化地图
     */
    public void initMapView() {
        mAMap = mMapView.getMap();
        mAMap.getUiSettings().setZoomControlsEnabled(false);     // 设置不显示缩放控件
        mAMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(MAP_SCALE));  // 设置缩放等级
        mAMap.setOnCameraChangeListener(this);

        //地理搜索类
        mGeocodeSearch = new GeocodeSearch(getContext());
        mGeocodeSearch.setOnGeocodeSearchListener(this);
        dingwei();
    }

    public void dingwei() {
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(getContext());
            mlocationClient.setLocationListener(this);
            mLocationOption = LocationUtil.getDefaultOption();
            mlocationClient.setLocationOption(mLocationOption);
            if (!fail) {
                mlocationClient.startLocation();
            }
        }
    }

    /**
     * 点击图中定位标志定位
     */
    private void againLoc() {
        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLoclatLng, MAP_SCALE));
        mlocationClient.startLocation();
        isLocal = false;
    }

    /**
     * 在屏幕中心添加一个Marker ,这个mark放哪  去哪里去搜索
     */
    private void addMarkerInScreenCenter() {
        if (mCenterMarkerOptions == null) {
            LatLng latLng = mAMap.getCameraPosition().target;
            Point screenPosition = mAMap.getProjection().toScreenLocation(latLng);
            mCenterMarkerOptions = new MarkerOptions().icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_mid_loc))
                    .zIndex(100)
                    .draggable(false);
            mCenterMarker = mAMap.addMarker(mCenterMarkerOptions);
            mCenterMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        } else {
            LatLng latLng = mAMap.getCameraPosition().target;
            Point screenPosition = mAMap.getProjection().toScreenLocation(latLng);
            mCenterMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        }
    }


    @Override
    public void onLocationChanged(AMapLocation amaplocation) {
        if (amaplocation != null) {
            if (amaplocation != null && amaplocation.getErrorCode() == 0) {
                if (!isLocal) {
                    mLoclatLng = new LatLng(amaplocation.getLatitude(), amaplocation.getLongitude());
                    //   mAMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));
                    // mlocationClient.stopLocation();
                    mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLoclatLng, MAP_SCALE), new AMap.CancelableCallback() {
                        @Override
                        public void onFinish() {
                            addMarkerInScreenCenter();
                            mlocationClient.stopLocation();
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
                    isLocal = true;
                }
            } else {
//                String errText = "failed to locate," + amaplocation.getErrorCode() + ": "
//                        + amaplocation.getErrorInfo();
//                ToastUitl.showLong(errText);
            }
        }
    }


    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LatLng latLng = new LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude);
        getAddressByLatlng(latLng);
    }

    private void getAddressByLatlng(LatLng latLng) {
        //逆地理编码查询条件：逆地理编码查询的地理坐标点、查询范围、坐标类型。
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500f, GeocodeSearch.AMAP);
        //异步查询
        mGeocodeSearch.getFromLocationAsyn(query);
        longitude = latLng.longitude;
        latitude = latLng.latitude;
    }

    //得到逆地理编码异步查询结果
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
        String formatAddress = regeocodeAddress.getFormatAddress();
//        ToastUitl.show(formatAddress, Toast.LENGTH_LONG);
        storeDetailedAreaText.setText(formatAddress);

    }


    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
        List<GeocodeAddress> addressList = geocodeResult.getGeocodeAddressList();
        if (addressList.size() != 0) {
            GeocodeAddress geocodeAddress = addressList.get(0);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    @AfterPermissionGranted(REQUEST_PERMISSION_LOCATION)
    public void needLoc() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION
                , Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            initMapView();
        } else {
            EasyPermissions.requestPermissions(this, "您需要定位权限",
                    REQUEST_PERMISSION_LOCATION, perms);
        }
    }


    @Override
    public String getContactName() {
        return contactNameEidt.getText().toString();
    }

    @Override
    public String getContactPhone() {
        return contactPhoneEidt.getText().toString();
    }

    @Override
    public String getLicenseName() {
        return licenseNameEidt.getText().toString();
    }

    @Override
    public String getLicenseNumber() {
        return LicenseNumberEidt.getText().toString();
    }

    @Override
    public String getBankNumber() {
        return bankCardEdidt.getText().toString();
    }

    @Override
    public String getBankPleName() {
        return bankCardNameEdidt.getText().toString();
    }

    @Override
    public String getBankCardPhotoUrl() {
        return bankCardPhotoUrl;
    }

    @Override
    public int intLongTime() {
        return radioIndex;
    }

    @Override
    public int storeProvinceid() {
        return provinceId;
    }

    @Override
    public int storeCityid() {
        return cityId;
    }

    @Override
    public int storeAreaid() {
        return areaId;
    }

    @Override
    public int storeStreetid() {
        return streetId;
    }

    @Override
    public String getAddress() {
        return areaText.getText().toString();
    }

    @Override
    public String getLicenseStartDate() {
        if (radioIndex == 0) {
            return "";
        } else {
            return licenseStartDate;
        }
    }

    @Override
    public String getLicenseEndDate() {
        if (radioIndex == 0) {
            return "";
        } else {
            return LicenseEndDate;
        }
    }

    @Override
    public String getHeadSfzNum() {
        return headSfzNumEdit.getText().toString();
    }

    @Override
    public String getStoreName() {
        return storeNameEdidt.getText().toString();
    }

    @Override
    public int operateRangeOne() {
        return intOperateRangeOne;
    }

    @Override
    public int operateRangeTwo() {
        return intOperateRangeTwo;
    }

    @Override
    public double getLongitude() {
        return longitude;
    }

    @Override
    public double getLatitude() {
        return latitude;
    }

    @Override
    public String getStoreDetail() {
        return storeDetailedAreaText.getText().toString();
    }

    @Override
    public String getBusinessLicenseUrl() {
        return businessLicenseUrl;
    }

    @Override
    public String getSfzPositiveUrl() {
        return sfzPositiveUrl;
    }

    @Override
    public String getSfzReverseUrl() {
        return sfzReverseUrl;
    }

    @Override
    public String getHoldSfzUrl() {
        return holdSfzUrl;
    }

    @Override
    public int getStoreType() {
        return storeType;
    }

    @Override
    public String getStorePhotoOneUrl() {
        return storePhotoOneUrl;
    }

    @Override
    public String getStorePhotoTwoUrl() {
        return storePhotoTwoUrl;
    }

    @Override
    public String getStorePhotoThreeUrl() {
        return storePhotoThreeUrl;
    }

    @Override
    public void setCategories(List<CategoriesBean> categoriesList) {
        for (int i = 0; i < categoriesList.size(); i++) {
            CategoriesBean categoriesBean = categoriesList.get(i);
            options1Items.add(categoriesBean);
            options1ItemName.add(categoriesBean.getValue());
        }
        initCustomOperateRange();
    }

    @Override
    public void setStoreCertificate(StoreCertificate storeCertificate,boolean isFromSave) {
        isTimeType = true;
        contactNameEidt.setText(storeCertificate.getOpenStoreDTO().getContactName());
        contactPhoneEidt.setText(storeCertificate.getOpenStoreDTO().getContactMobile());
        licenseNameEidt.setText(storeCertificate.getOpenStoreDTO().getCompanyName());
        LicenseNumberEidt.setText(storeCertificate.getOpenStoreDTO().getLicenseNumber());

        operateRangeOne.setText(storeCertificate.getOpenStoreDTO().getStoreType1Name());
        storeTypeNameOne = storeCertificate.getOpenStoreDTO().getStoreType1Name();

        operateRangeTwo.setText(storeCertificate.getOpenStoreDTO().getStoreType2Name());
        storeTypeNameTwo = storeCertificate.getOpenStoreDTO().getStoreType2Name();

        bankCardEdidt.setText(storeCertificate.getOpenStoreDTO().getBankCardNo());
        bankCardNameEdidt.setText(storeCertificate.getOpenStoreDTO().getBankCardUserName());
        if (storeCertificate.getOpenStoreDTO().getIsLongTime() == 0) {
            radioLongTime.setChecked(true);
            isTimeType = false;
        } else {
            radioTimeInterval.setChecked(true);
            timeText.setVisibility(View.VISIBLE);
            String startTime,endTime;
            if(isFromSave){
                 startTime = storeCertificate.getOpenStoreDTO().getLicenseStartDate();
                 endTime = storeCertificate.getOpenStoreDTO().getLicenseEndDate();
            }else{
                 startTime = TimeUitl.longToDate(storeCertificate.getOpenStoreDTO().getLicenseStartDate());
                 endTime = TimeUitl.longToDate(storeCertificate.getOpenStoreDTO().getLicenseEndDate());
            }
            timeText.setText(startTime + "至" + endTime);
            licenseStartDate = startTime;
            LicenseEndDate = endTime;
        }
        radioIndex = storeCertificate.getOpenStoreDTO().getIsLongTime();
        provinceId = storeCertificate.getOpenStoreDTO().getStoreProvinceid();
        cityId = storeCertificate.getOpenStoreDTO().getStoreCityid();
        areaId = storeCertificate.getOpenStoreDTO().getStoreAreaid();
        streetId = storeCertificate.getOpenStoreDTO().getStoreStreetid();
        //storeType = storeCertificate.getOpenStoreDTO().getType();
        headSfzNumEdit.setText(storeCertificate.getOpenStoreDTO().getIdCardNum());
        storeNameEdidt.setText(storeCertificate.getOpenStoreDTO().getName());
        intOperateRangeOne = storeCertificate.getOpenStoreDTO().getStoreType1();
        intOperateRangeTwo = storeCertificate.getOpenStoreDTO().getStoreType2();
        if(!TextUtils.isEmpty(storeCertificate.getOpenStoreDTO().getStoreProvinceName())){
            areaText.setText(storeCertificate.getOpenStoreDTO().getStoreProvinceName() + storeCertificate.getOpenStoreDTO().getStoreCityName()
                    + storeCertificate.getOpenStoreDTO().getStoreAreaName() + storeCertificate.getOpenStoreDTO().getStoreStreetName());
            provinceName = storeCertificate.getOpenStoreDTO().getStoreProvinceName();
            cityName = storeCertificate.getOpenStoreDTO().getStoreCityName();
            areaName = storeCertificate.getOpenStoreDTO().getStoreAreaName();
            streetName = storeCertificate.getOpenStoreDTO().getStoreStreetName();
        }
        storeDetailedAreaText.setText(storeCertificate.getOpenStoreDTO().getStoreAddr());

        if(!TextUtils.isEmpty(storeCertificate.getOpenStoreDTO().getBankCardImg())){
            ImageLoadUtil.displayImage(getContext(), storeCertificate.getOpenStoreDTO().getBankCardImg(), bankCardPhoto.getPhotoView(), R.drawable.ic_download_fail);
            bankCardPhoto.setSuccessView();
        }

        if(!TextUtils.isEmpty(storeCertificate.getOpenStoreDTO().getCompany())){
            ImageLoadUtil.displayImage(getContext(), storeCertificate.getOpenStoreDTO().getCompany(), businessLicenseImg.getPhotoView(), R.drawable.ic_download_fail);
            businessLicenseImg.setSuccessView();
        }

        if(!TextUtils.isEmpty(storeCertificate.getOpenStoreDTO().getCard())){
            ImageLoadUtil.displayImage(getContext(), storeCertificate.getOpenStoreDTO().getCard(), sfzPositiveImg.getPhotoView(), R.drawable.ic_download_fail);
            sfzPositiveImg.setSuccessView();
        }

        if(!TextUtils.isEmpty(storeCertificate.getOpenStoreDTO().getCardback())){
            ImageLoadUtil.displayImage(getContext(), storeCertificate.getOpenStoreDTO().getCardback(), sfzReverseImg.getPhotoView(), R.drawable.ic_download_fail);
            sfzReverseImg.setSuccessView();
        }

        if(!TextUtils.isEmpty(storeCertificate.getOpenStoreDTO().getStore())){
            ImageLoadUtil.displayImage(getContext(), storeCertificate.getOpenStoreDTO().getStore(), storePhotoImgOne.getPhotoView(), R.drawable.ic_download_fail);
            storePhotoImgOne.setSuccessView();
        }

        if(!TextUtils.isEmpty(storeCertificate.getOpenStoreDTO().getHandcard())){
            ImageLoadUtil.displayImage(getContext(), storeCertificate.getOpenStoreDTO().getHandcard(), holdSfzImg.getPhotoView(), R.drawable.ic_download_fail);
            holdSfzImg.setSuccessView();
        }



//        ImageLoadUtil.displayImage(getContext(), storeCertificate.getOpenStoreDTO().getHandcard(), holdSfzImg.getPhotoView(), R.drawable.ic_download_fail);

//        ImageLoadUtil.displayImage(getContext(), storeCertificate.getOpenStoreDTO().getCashierDesk(), storePhotoImgTwo.getPhotoView(), R.drawable.ic_download_fail);
//        ImageLoadUtil.displayImage(getContext(), storeCertificate.getOpenStoreDTO().getStore(), storePhotoImgThree.getPhotoView(), R.drawable.ic_download_fail);

        businessLicenseUrl = storeCertificate.getOpenStoreDTO().getCompany();
        sfzPositiveUrl = storeCertificate.getOpenStoreDTO().getCard();
        sfzReverseUrl = storeCertificate.getOpenStoreDTO().getCardback();
        holdSfzUrl = storeCertificate.getOpenStoreDTO().getHandcard();
        storePhotoOneUrl = storeCertificate.getOpenStoreDTO().getStore();
//        storePhotoTwoUrl = storeCertificate.getOpenStoreDTO().getCashierDesk();
//        storePhotoThreeUrl = storeCertificate.getOpenStoreDTO().getStore();
        bankCardPhotoUrl  = storeCertificate.getOpenStoreDTO().getBankCardImg();
        longitude = Double.parseDouble(storeCertificate.getOpenStoreDTO().getLongitude());
        latitude = Double.parseDouble(storeCertificate.getOpenStoreDTO().getLatitude());
        double[] baiduPoint = GPSUtil.bd09_To_Gcj02(latitude, longitude);
        mLoclatLng = new LatLng(baiduPoint[0], baiduPoint[1]);
        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLoclatLng, MAP_SCALE), new AMap.CancelableCallback() {
            @Override
            public void onFinish() {
                addMarkerInScreenCenter();
            }

            @Override
            public void onCancel() {
            }
        });
    }

    @Override
    public void setProvinces(ArrayList<City> cityList) {
        provincesList = cityList;
        showAddressPickerPop();
    }

    @Override
    public void setCitys(ArrayList<City> cityList, AddressSelector addressSelector, int postion) {
        citysList.clear();
        citysList = cityList;
        addressSelector.setCities(citysList);

    }

    @Override
    public void setAreas(ArrayList<City> cityList, AddressSelector addressSelector, int postion) {
        if (cityList.size() < 1) {
            areaText.setText(provinceName + cityName);
            bottomSheetDialog.dismiss();
        } else {
            areasList.clear();
            areasList = cityList;
            addressSelector.setCities(areasList);
        }

    }

    @Override
    public void setStreets(ArrayList<City> cityList, AddressSelector addressSelector, int postion) {
        if (cityList.size() < 1) {
            areaText.setText(provinceName + cityName + areaName);
            bottomSheetDialog.dismiss();
        } else {
            streetsList.clear();
            streetsList = cityList;
            addressSelector.setCities(streetsList);
        }
    }

    @Override
    public void notEmpty() {
        if (!isUploading()) {
            mPresenter.StoreCertificateSub();
        } else {
            ToastUitl.show("图片正在上传，请稍后。。。", Toast.LENGTH_SHORT);
        }

    }


    @Override
    public void onUpViewClick(View view) {
        if (view.getId() == R.id.business_license_img) {
            mSelectUpView = businessLicenseImg;
        } else if (view.getId() == R.id.sfz_positive_img) {
            mSelectUpView = sfzPositiveImg;
        } else if (view.getId() == R.id.sfz_reverse_img) {
            mSelectUpView = sfzReverseImg;
        } else if (view.getId() == R.id.hold_sfz_img) {
            mSelectUpView = holdSfzImg;
        } else if (view.getId() == R.id.store_photo_img_one) {
            mSelectUpView = storePhotoImgOne;
        } else if (view.getId() == R.id.store_photo_img_two) {
            mSelectUpView = storePhotoImgTwo;
        } else if (view.getId() == R.id.store_photo_img_three) {
            mSelectUpView = storePhotoImgThree;
        }else if (view.getId() == R.id.bank_card_photo) {
            mSelectUpView = bankCardPhoto;
        }
    }


    class VisibleScheduledExecutor implements Runnable {

        @Override
        public void run() {
            Message msg = new Message();
            msg.what = 1;
            mHandle.sendMessage(msg);
        }
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图

    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
    }

    @Override
    public void onDestroy() {

        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
        mLocationOption = null;
        if (service != null) {
            if (!service.isShutdown()) {
                service.shutdown();
            }
        }

        super.onDestroy();
    }

    private void closeKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (mSelectUpView.getResultListener() != null) {
                    mSelectUpView.getResultListener().setSelectedImages(images);
                }
            } else {
                Toast.makeText(getContext(), "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    public String getStoreTypeNameOne(){
        if(TextUtils.isEmpty(storeTypeNameOne)){
            return "";
        }else{
            return storeTypeNameOne;
        }
    }


    @Override
    public String getStoreTypeNameTwo(){
        if(TextUtils.isEmpty(storeTypeNameTwo)){
            return "";
        }else{
            return storeTypeNameTwo;
        }
    }


    @Override
    public String getStoreProvinceName(){
        if(TextUtils.isEmpty(provinceName)){
            return "";
        }else{
            return provinceName;
        }
    }

    @Override
    public String getStoreCityName(){
        if(TextUtils.isEmpty(cityName)){
            return "";
        }else{
            return cityName;
        }
    }

    @Override
    public String getStoreAreaName(){
        if(TextUtils.isEmpty(areaName)){
            return "";
        }else{
            return areaName;
        }
    }
    
    @Override
    public String getStoreStreetName(){
        if(TextUtils.isEmpty(streetName)){
            return "";
        }else{
            return streetName;
        }
    }

    public void saveData(){
        mPresenter.saveData();
    }


}
